package a_doubleWrite;

import java.util.Arrays;
import java.util.Random;

/**
 * todo
 *
 * @author: luolidong
 * @create: 2021-07-19 17:23
 * @version: 1.0
 */
public class L215_quickSort {
    public void quickSort(int[] nums, int left, int right) {
        if (left >= right) return;
        int mid = getRandomP(nums, left, right);
        System.out.println("left");
        for (int i = 0; i < mid; i++) {
            System.out.println(nums[i]);
        }
        System.out.println("mid :" + nums[mid]);
        for (int i = mid + 1; i <= right; i++) {
            System.out.println(nums[i]);
        }
        System.out.println("right");
        quickSort(nums, left, mid - 1);
        quickSort(nums, mid + 1, right);
    }

    private int partition(int[] nums, int left, int right) {
        int p = nums[left];//基准值
        int l = left;
        int r = right;
        while (l < r) {
            while (l < r && nums[r] > p) {//向左找小于等于p的数
                r--;
            }
            /* nums[l] <= p 需要=,因为l从基准值开始，需要跳过 */
            while (l < r && nums[l] <= p) {
                l++;
            }
            if (l < r) {
                swap(nums, l, r);
            }
        }
        swap(nums, left, l);
        return l;//基准值位置
    }

    public void swap(int[] nums, int l, int r) {
        int temp = nums[l];
        nums[l] = nums[r];
        nums[r] = temp;

    }

    //获取随机基准值
    public int getRandomP(int[] nums, int start, int end) {
//        Random random = new Random();
//        int i = random.nextInt(end + 1 - start) + start;
//        System.out.println("基准值" + nums[i]);
//        swap(nums, start, i);
        return partition(nums, start, end);
    }

    public static void main(String[] args) {
        int[] nums = {1, 5, 2, 4, 3};
        new L215_quickSort().quickSort(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }
}
